package com.contain.bootelasticsearch.data;

import com.contain.bootelasticsearch.bean.JDGoods;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: tianchao
 * @Date: 2021/3/4 18:04
 * @Description:
 */
@Component
public class DataUtils {

    public static void main(String[] args) throws IOException {
        new DataUtils().parseSearch("java");
    }

    public List<Object> parseSearch(String keyword){
        String url = "https://search.jd.com/Search?keyword=" + keyword;
        Document document = null;
        try {
            document = Jsoup.parse(new URL(url), 5000);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        Element goodList = document.getElementById("J_goodsList");
        Elements items = goodList.getElementsByClass("gl-item");
        List<Object> list = new ArrayList<>();
        for (int i =0;i<items.size();i++){
            Element item = items.get(i);
            String img = item.getElementsByClass("p-img").get(0).getElementsByTag("img").get(0).attr("data-lazy-img");
            String price = item.getElementsByClass("p-price").get(0).getElementsByTag("i").text();
            String title = item.getElementsByClass("p-name").text();
            JDGoods jdGoods = new JDGoods();
            jdGoods.setImg(img);
            jdGoods.setPrice(price);
            jdGoods.setTitle(title);
            list.add(jdGoods);
        }
        return list;
    }
}
